﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using DataGeneration.Domain.DataAccessLayer;
using DataGeneration.Domain.Helpers;
using DataGeneration.Domain.Logging;

namespace DataGeneration.Domain.Logic
{
    public class SqlBatchManager
    {
        StringBuilder SqlContainer { get; set; }
        public SqlBatchManager()
        {
            SqlContainer=new StringBuilder();
        }

        public void AddSqlStatement(string sqlStatement)
        {
            SqlContainer.Append(string.Format("{0};", sqlStatement));
        }

        public void ExecuteBatch(DataAccess dataAccess, string patternName, int batchNo, bool insertIntoDb)
        {
            try
            {
                string aval = string.Format("BEGIN {0} END;", SqlContainer.ToString());
                FileHelper.SaveToFile(ParameterizedAppSettings.GenerateBatchFilename(patternName, batchNo), aval);
                if (insertIntoDb)
                {
                    dataAccess.InitializeCommand(aval, CommandType.Text);
                    dataAccess.ExecuteCommand();
                }
            }
            catch (Exception exception)
            {
                Logger.WriteMessage(string.Format("Failed while executing statement:\n {0}", SqlContainer.ToString()));
                Logger.WriteMessage(exception.Message);
                throw;
            }
        }
    }
}
